package com.qf.util.qiniu.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;  
import org.apache.commons.logging.impl.Log4JLogger;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import sun.misc.BASE64Decoder;

import com.google.gson.Gson;
import com.qf.system.peilian.service.PeilianService;
import com.qf.system.userinfo.service.UserInfoService;
import com.qf.util.Base64AndPicture;
import com.qf.util.PageData;
import com.qf.util.controller.BaseController;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

@Controller
@RequestMapping(value="/picture")
public class QiniuUploadController extends BaseController {
	
	private Log4JLogger log=new Log4JLogger();
   	@Resource(name="userinfoService")
	private UserInfoService userinfoService;
	@Resource(name="peilianService")
	private PeilianService peilianService;
	Auth auth = Auth.create("LD5uBW1UGlUUk5fyYgv0v7aDcNswYZHGc3LWYcsJ", "K5NyrqmXbVUTHQkvQKddDSE9zA1inNngjUarxxsE");
	@RequestMapping("addPhoto")
	public void addPhoto(HttpServletRequest request,HttpServletResponse response) throws IOException{
		PageData pd=new PageData();
		pd=this.getPageData();
		  UploadManager uploadManager = new UploadManager();
		  response.setContentType("text/html;charset=utf-8");
	        //创建一个通用的多部分解析器  
	        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
	        //判断 request 是否有文件上传,即多部分请求  
	        if(multipartResolver.isMultipart(request)){  
	            //转换成多部分request    
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
	            //取得request中的所有文件名  
	            Iterator<String> iter = multiRequest.getFileNames();  
	            while(iter.hasNext()){  
	                //取得上传文件  
	                MultipartFile file = multiRequest.getFile(iter.next());  
	                if(file != null){  
	                    //取得当前上传文件的文件名称  
	                    String myFileName = file.getOriginalFilename();  
	                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在  
	                    if(myFileName.trim() !=""){  
	                        //重命名上传后的文件名  
	                        //定义上传路径  
	           
	                        
	                        //创建文件唯一名称  
		                    String uuid = UUID.randomUUID().toString();  
		                    //检查文件后缀格式  
                 
		             
		                    try {
		                    	String token=getUpToken();
		        	        Response res = uploadManager.put(file.getBytes(), uuid, token);
		        	        // log.info(res);
		        	        // log.info(res.bodyString());
		        	        // Ret ret = res.jsonToObject(Ret.class);
		        	        if(pd.getString("type").equals("ancestral")){
//		        	        appAncestralHallService.saveAncestralHallAlbum(pd.getString("ancestral_hall_obid"), "http://7xkccy.com2.z0.glb.qiniucdn.com/"+uuid);
		        	        }
		        	        if(pd.getString("type").equals("user")){
		        	        	Map map=new HashMap();
		        	        	map.put("picurl", "http://7xocaw.com1.z0.glb.clouddn.com/"+uuid);
		        	        	map.put("user_id",pd.getString("user_id"));
		        	        	map.put("addtime", System.currentTimeMillis()/1000);
		        	        	userinfoService.addphoto(map);
		        	        }
		        	        if(pd.getString("type").equals("peilian")){
		        	        	Map map=new HashMap();
		        	        	map.put("picurl", "http://7xocaw.com1.z0.glb.clouddn.com/"+uuid);
		        	        	map.put("pl_id",pd.getString("pl_id"));
		        	        	map.put("addtime", System.currentTimeMillis()/1000);
		        	        	peilianService.addphoto(map);
		        	        }
		        	        System.out.println("http://7xocaw.com1.z0.glb.clouddn.com/"+uuid);
		                    response.getWriter().write("success");
		        	    } catch (QiniuException e) {
		        	        // 请求失败时简单状态信息
		        	        Response r = e.response;
		        	        // 请求失败时简单状态信息
		        	        System.out.println(r.toString());
		        	        try {
		        	            // 响应的文本信息
		        	            System.out.println(r.bodyString());
		        	        } catch (QiniuException e1) {
		        	            //ignore
		        	        }
		        	    }
	                        
	                    }  
	                }  
	            }

	}
	}
	        	// 简单上传，使用默认策略
	        	private String getUpToken(){
	        		String token=auth.uploadToken("wuxian",null,24*60*1000,null);
	        		System.out.println(token);
        	    return token;
	        	}
	        	/**保存图片
	        	 * @param imgStr
	        	 * @param session
	        	 * @param request
	        	 * @param response
	        	 * @throws IOException
	        	 */
	        	@RequestMapping("savePic")
	        	public @ResponseBody void savePic(String imgStr,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws IOException{
	                PrintWriter out =response.getWriter();
	          	  UploadManager uploadManager = new UploadManager();
	          	 BASE64Decoder decoder = new BASE64Decoder();  
	        		String imgUrl="";
	        		if(!imgStr.equals("") && imgStr!=null){
	        		
	        			imgStr = imgStr.split(";base64,")[1];
	      
	        		    //创建文件唯一名称  
	                    String uuid = UUID.randomUUID().toString();  
	                    //检查文件后缀格式  
	                       String token= getUpToken();
	        			   Response res = uploadManager.put(decoder.decodeBuffer(imgStr), uuid,token);
	        			   imgUrl="http://7xocaw.com1.z0.glb.clouddn.com/"+uuid;
	        			if(imgUrl!=null){
	        			};
	        		}
	        	   Gson g= new Gson();
	        	   Map<String, String> map=new HashMap<String, String>();
	        	   map.put("imgUrl", imgUrl);
	        	   String a= g.toJson(map);
	        	   out.print(a);
	        	   out.flush();
	        	   out.close();
	        	}      	
	        	
	        	public void putb64(String imgStr) throws Exception {
	        	    try{
	        	        int l =imgStr.length();
	        	    
	        	        String file64 = imgStr;
	        	        String url = "http://up.qiniu.com/putb64/" + l;
	        	        System.out.println(url);
	        	        HttpPost post = new HttpPost(url);
	        	        post.addHeader("Content-Type", "application/octet-stream");
	        	        post.addHeader("Authorization", "UpToken " + getUpToken());
	        	        System.out.println( "UpToken " + getUpToken());
	        	        //post.setEntity(new ByteArrayEntity(src));
	        	        post.setEntity(new StringEntity(file64));
	        	        System.out.println(file64);
	                   HttpClient c = new DefaultHttpClient();
	        	        HttpResponse res = c.execute(post);
	        	        System.out.println(res.getStatusLine());
	        	        String responseBody = EntityUtils.toString(
	        	                res.getEntity(), "UTF-8");
	        	        System.out.println(responseBody);
	        	    }catch(Exception e){
	        	        e.printStackTrace();
	        	        throw e;
	        	    }
	        	}
	
}
